package com.tianji.learning.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.cache.CategoryCache;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CategoryClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.client.search.SearchClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CategoryBasicDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionAdminPageQuery;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2025-10-25
 */
@Service
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {
    private final IInteractionReplyService replyService;
    private final UserClient userClient;
    private final SearchClient searchClient;
    private final CourseClient courseClient;
    private final CatalogueClient catalogueClient;
    private final CategoryClient categoryClient;
    private final CategoryCache categoryCache;

    @Override
    public void saveQuestion(QuestionFormDTO formDTO) {
        // 0、问题内容合规性检测 TODO

        // 1、数据拷贝
        InteractionQuestion question = BeanUtils.toBean(formDTO, InteractionQuestion.class);

        // 2、补充用户ID
        question.setUserId(UserContext.getUser());

        // 3、新增
        this.save(question);
    }

    @Override
    public PageDTO<QuestionVO> pageQuery(QuestionPageQuery pageQuery) {
        // 1、参数校验
        Long courseId = pageQuery.getCourseId();
        Long sectionId = pageQuery.getSectionId();
        if (ObjectUtil.isEmpty(courseId) && ObjectUtil.isEmpty(sectionId)) {
            throw new BadRequestException("课程ID和小节ID不能同时为空");
        }

        // 2、分页查询
        // select * from interaction_question where couse_id = ? and section_id = ? and user_id = ? and hidden = 0
        // order by create_time desc limit ?,?
        Page<InteractionQuestion> pageResult = this.lambdaQuery()
                .select(InteractionQuestion.class, tableFieldInfo -> ObjectUtil.notEqual(tableFieldInfo.getColumn(), "description"))
                .eq(ObjectUtil.isNotEmpty(courseId), InteractionQuestion::getCourseId, courseId)
                .eq(ObjectUtil.isNotEmpty(sectionId), InteractionQuestion::getSectionId, sectionId)
                .eq(pageQuery.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(InteractionQuestion::getHidden, false)
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(pageResult);
        }

        // 3、补充信息查询：查询 提问者信息（非匿名）、查询最近一次回答信息（最近一次回答内容、最近回答者ID）
        // 3.1、收集提问者ID集合、收集最近一次回答ID集合
        /*Set<Long> userIds = records.stream().filter(q -> !q.getAnonymity()).map(InteractionQuestion::getUserId).collect(Collectors.toSet());
        Set<Long> lastAnswerIds = CollStreamUtil.toSet(records, InteractionQuestion::getLatestAnswerId);*/
        Set<Long> userIds = new HashSet<>(records.size());
        Set<Long> lastAnswerIds = new HashSet<>(records.size());
        for (InteractionQuestion record : records) {
            if (!record.getAnonymity()) {
                userIds.add(record.getUserId());
            }
            lastAnswerIds.add(record.getLatestAnswerId());
        }
        lastAnswerIds.remove(null);

        // 3.2、根据最近一次回答ID集合 查询 最近一次回答信息，封装成Map（最近一次回答ID：最近一次回答对象）
        List<InteractionReply> lastReplyList = new ArrayList<>(lastAnswerIds.size());
        if (ObjectUtil.isNotEmpty(lastAnswerIds)) {
            lastReplyList = replyService.listByIds(lastAnswerIds);
        }
        /*Map<Long, InteractionReply> replyMap = CollStreamUtil.toIdentityMap(lastReplyList, InteractionReply::getId);
        Set<Long> replyUserIds = lastReplyList.stream().filter(reply -> !reply.getAnonymity()).map(reply -> reply.getUserId()).collect(Collectors.toSet());
        userIds.addAll(replyUserIds);*/
        Map<Long, InteractionReply> replyMap = new HashMap<>(lastReplyList.size());
        if (ObjectUtil.isNotEmpty(lastReplyList)) {
            for (InteractionReply reply : lastReplyList) {
                replyMap.put(reply.getId(), reply);
                if (!reply.getAnonymity()) {
                    userIds.add(reply.getUserId());
                }
            }
        }

        // 3.3、根据提问者ID集合 查询 提问者用户信息，封装成Map（用户ID：用户信息对象）
        List<UserDTO> userInfoList = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userInfoMap = new HashMap<>(userInfoList.size());
        if (ObjectUtil.isNotEmpty(userInfoList)) {
            userInfoMap = CollStreamUtil.toIdentityMap(userInfoList, UserDTO::getId);
        }

        // 4、循环遍历当前页码分页数据，封装vo集合
        List<QuestionVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            // 4.1、将po转为vo（拷贝）
            QuestionVO vo = BeanUtils.copyBean(record, QuestionVO.class);

            // 4.2、补充提问者信息（昵称、头像）
            if (!record.getAnonymity()) {
                UserDTO userInfo = userInfoMap.get(record.getUserId());
                if (ObjectUtil.isNotEmpty(userInfo)) {
                    vo.setUserName(userInfo.getName());
                    vo.setUserIcon(userInfo.getIcon());
                }
            }

            // 4.3、补充最近一次回答信息（回答内容、回答者昵称）
            InteractionReply lastReply = replyMap.get(record.getLatestAnswerId());
            if (ObjectUtil.isNotEmpty(lastReply)) {
                vo.setLatestReplyContent(lastReply.getContent());
                if (!lastReply.getAnonymity()) {
                    UserDTO userInfo = userInfoMap.get(lastReply.getUserId());
                    if (ObjectUtil.isNotEmpty(userInfo)) {
                        vo.setLatestReplyUser(userInfo.getName());
                    }
                }
            }

            // 4.4、添加vo到集合
            voList.add(vo);
        }

        // 5、封装分页结果返回
        return PageDTO.of(pageResult, voList);
    }

    @Override
    public QuestionVO queryById(Long id) {
        // 1、根据ID查询问题
        InteractionQuestion question = this.getById(id);
        if (ObjectUtil.isEmpty(question) || question.getHidden()) {
            return null;
        }

        // 2、查询提问者信息
        /*UserDTO userInfo = null;
        if (!question.getAnonymity()) {
            userInfo = userClient.queryUserById(question.getUserId());
        }*/

        // 3、封装Vo返回
        /*QuestionVO vo = BeanUtils.copyBean(question, QuestionVO.class);
        if (ObjectUtil.isNotEmpty(userInfo)) {
            vo.setUserName(userInfo.getName());
            vo.setUserIcon(userInfo.getIcon());
        }*/

        QuestionVO vo = BeanUtils.copyBean(question, QuestionVO.class);
        if (!question.getAnonymity()) {
            UserDTO userInfo = userClient.queryUserById(question.getUserId());
            if (ObjectUtil.isNotEmpty(userInfo)) {
                vo.setUserName(userInfo.getName());
                vo.setUserIcon(userInfo.getIcon());
            }
        }
        return vo;
    }

    @Override
    public PageDTO<QuestionAdminVO> adminPageQuery(QuestionAdminPageQuery pageQuery) {
        // 1、调用ES处理课程名称，得到课程ID集合
        List<Long> couseIds = null;
        if (StrUtil.isNotBlank(pageQuery.getCourseName())) {
            couseIds = searchClient.queryCoursesIdByName(pageQuery.getCourseName());
            if (ObjectUtil.isEmpty(couseIds)) {
                return PageDTO.empty(0L, 0L);
            }
        }

        // 2、分页查询问题列表
        // select * from interaction_question where couse_id in (?) and status = ? and create_time >= ? and create_time <= ?
        // order by create_time desc limit ?,?
        Page<InteractionQuestion> pageResult = this.lambdaQuery()
                .in(ObjectUtil.isNotEmpty(couseIds), InteractionQuestion::getCourseId, couseIds)
                .eq(ObjectUtil.isNotEmpty(pageQuery.getStatus()), InteractionQuestion::getStatus, pageQuery.getStatus())
                .ge(ObjectUtil.isNotEmpty(pageQuery.getBeginTime()), InteractionQuestion::getCreateTime, pageQuery.getBeginTime())
                .le(ObjectUtil.isNotEmpty(pageQuery.getEndTime()), InteractionQuestion::getCreateTime, pageQuery.getEndTime())
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(pageResult);
        }

        // 3、补充信息查询（章节数据、课程数据、用户数据）
        // 3.0、收集各种业务ID集合
        Set<Long> userIds = new HashSet<>(records.size());
        Set<Long> cIds = new HashSet<>(records.size());
        Set<Long> cataIds = new HashSet<>(records.size());
        for (InteractionQuestion record : records) {
            userIds.add(record.getUserId());
            cIds.add(record.getCourseId());

            cataIds.add(record.getChapterId());
            cataIds.add(record.getSectionId());
        }

        // 3.1、根据用户ID集合查询用户信息，转为Map（用户ID：用户昵称）
        List<UserDTO> userInfoList = userClient.queryUserByIds(userIds);
        Map<Long, String> userInfoMap = new HashMap<>(userIds.size());
        if (ObjectUtil.isNotEmpty(userInfoList)) {
           userInfoMap = CollStreamUtil.toMap(userInfoList, UserDTO::getId, UserDTO::getName);
        }

        // 3.2、根据课程ID集合查询课程信息，转为Map（课程ID：课程信息对象）
        List<CourseSimpleInfoDTO> couseInfoList = courseClient.getSimpleInfoList(cIds);
        Map<Long, CourseSimpleInfoDTO> couseInfoMap = new HashMap<>(cIds.size());
        if (ObjectUtil.isNotEmpty(couseInfoList)) {
            couseInfoMap = CollStreamUtil.toIdentityMap(couseInfoList, CourseSimpleInfoDTO::getId);
        }

        // 3.3、根据章节ID集合查询章节信息，转为Map（章节ID：章节名称）
        List<CataSimpleInfoDTO> cataInfoList = catalogueClient.batchQueryCatalogue(cataIds);
        Map<Long, String> cataInfoMap = new HashMap<>(cataIds.size());
        if (ObjectUtil.isNotEmpty(cataInfoList)) {
            cataInfoMap = CollStreamUtil.toMap(cataInfoList, CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName);
        }

        // 4、循环分页列表数据，封装vo集合
        List<QuestionAdminVO> voList = new ArrayList<>(records.size());

        /*List<CategoryBasicDTO> allOfOneLevelList = categoryClient.getAllOfOneLevel();
        Map<Long, String> allCategoryMap = CollStreamUtil.toMap(allOfOneLevelList, CategoryBasicDTO::getId, CategoryBasicDTO::getName);*/
        for (InteractionQuestion question : records) {
            // 4.1、属性拷贝（po -> vo）
            QuestionAdminVO vo = BeanUtils.copyBean(question, QuestionAdminVO.class);
            vo.setAnswerAmounts(question.getAnswerTimes());

            // 4.2、填充章节名称
            vo.setChapterName(cataInfoMap.getOrDefault(question.getChapterId(),""));
            vo.setSectionName(cataInfoMap.getOrDefault(question.getSectionId(),""));

            // 4.3、填充提问者昵称
            vo.setUserName(userInfoMap.getOrDefault(question.getUserId(),""));

            // 4.4、填充课程名称 和 三级分类信息
            CourseSimpleInfoDTO courseInfo = couseInfoMap.get(question.getCourseId());
            if(ObjectUtil.isNotEmpty(courseInfo)){
                vo.setCourseName(courseInfo.getName());
                // 已知课程三级分类ID ->  三级分类名称 拼接字符串，示例：一级分类/二级分类/三级分类
                /*String firstCataName = allCategoryMap.get(courseInfo.getFirstCateId());
                String secondCataName = allCategoryMap.get(courseInfo.getSecondCateId());
                String thridCataName = allCategoryMap.get(courseInfo.getThirdCateId());
                String categoryName = List.of(firstCataName, secondCataName, thridCataName).stream().collect(Collectors.joining("/"));*/
                vo.setCategoryName(categoryCache.getCategoryNames(courseInfo.getCategoryIds()));
            }

            // 4.5、添加至vo集合
            voList.add(vo);
        }

        // 5、封装分页数据并返回
        return PageDTO.of(pageResult,voList);
    }
}
